package com.dl.debugtools.api

import com.dl.base.AppContext
import com.dl.base.BaseApplication
import com.dl.base.api.response.awaitBoolean
import com.dl.base.api.response.awaitFile
import com.dl.base.api.response.awaitResult
import com.dl.base.api.websocket.bean.WebSocketInfo
import com.dl.debugtools.DebugToolsPreferences
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers

class DebugToolsRepository {
    private val api = BaseApplication.retrofitCreate(DebugToolsService::class.java)
    private val webSocket = BaseApplication.webSocketCreate()
    private var commandUrl: String = "${AppContext.webSocketUrl}/comm/command/1/"
    private var installUrl: String = "${AppContext.webSocketUrl}/comm/install/1/"

    suspend fun generateDevice() =
        awaitResult { api.generateDevice(GenerateDeviceDTO(DebugToolsPreferences.deviceName)) }

    suspend fun setDeviceName(name: String) =
        awaitBoolean { api.generateDevice(GenerateDeviceDTO(name)) }

    fun loadUrl(id: Int) {
        commandUrl = "${AppContext.webSocketUrl}/comm/command/${id}/"
        installUrl = "${AppContext.webSocketUrl}/comm/install/${id}/"
    }

    fun subscribeCommand(): Observable<WebSocketInfo> {
        return webSocket[commandUrl]
    }

    fun sendCommandResult(msg: String) {
        webSocket.send(commandUrl, msg).subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io()).subscribe({}, {})
    }

    fun subscribeInstall(): Observable<WebSocketInfo> {
        return webSocket[installUrl]
    }

    /**
     * 下载文件
     */
    suspend fun downloadFile(filePath: String, url: String) = awaitFile(filePath) {
        api.downloadFile(url)
    }

    companion object {
        val instance: DebugToolsRepository by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            DebugToolsRepository()
        }
    }
}